package com.kaifamiao.month04.day28.work;

import java.io.*;
import java.util.*;

public class SortFile {

    public void sortFile(File original, File directory) throws IOException {
        // 检测目标文件是否存在
        if (!original.exists() && !original.isFile())  throw new FileNotFoundException("文件不存在！");
        // 检测文件的路径是否存在
        if (!directory.getParentFile().exists()) directory.getParentFile().mkdirs();
        FileReader in = new FileReader(original);
        BufferedReader reader = new BufferedReader(in);
        List<String> list = new ArrayList<>();
        String str;
        while ((str = reader.readLine()) != null)
            list.add(str);
        reader.close();
        in.close();
        FileWriter out = new FileWriter(directory, true);
        BufferedWriter w = new BufferedWriter(out);
        list.sort((o1, o2) -> Integer.parseInt(o1.substring(0, o1.indexOf('.'))) - Integer.parseInt(o2.substring(0, o2.indexOf('.'))));
        for (String s : list) {
            w.write(s);
            w.newLine();
        }
        w.flush();
        out.flush();
        w.close();
        out.close();
    }

    public void sortFile2(File original, File directory) throws IOException {
        int count = 0;
        // 检测目标文件是否存在
        if (!original.exists() && !original.isFile())  throw new FileNotFoundException("文件不存在！");
        // 检测文件的路径是否存在
        if (!directory.exists()) directory.mkdirs();
        FileReader in = new FileReader(original);
        BufferedReader reader = new BufferedReader(in);
        List<String> list = new ArrayList<>();
        String str;
        while ((str = reader.readLine()) != null)
            list.add(str);
        reader.close();
        in.close();
        FileWriter out;
        for (String s : list) {
            out = new FileWriter(directory.getAbsolutePath() + "\\" + System.nanoTime() + ".temp");
            out.write(s);
            out.flush();
            out.close();
        }
    }

    public static void main(String[] args) throws IOException {
        File original = new File("E:\\1101\\test\\temp\\work28\\test28.txt");
        File directory = new File("E:\\1101\\test\\temp\\work28\\temp");
        SortFile sf = new SortFile();
        sf.sortFile2(original, directory);
    }
}
